package com.boe.server.register.security.handler;

import com.boe.server.register.config.JWTConfig;
import com.boe.server.register.util.JWTTokenUtil;
import com.boe.server.register.util.ResultUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 登录成功处理类
 *
 * @author uaniheng
 * @CreateTime 2019/10/3 9:13
 */
@Component
public class UserLoginSuccessHandler implements AuthenticationSuccessHandler {

    private final JWTTokenUtil jwtTokenUtil;

    private final JWTConfig jwtConfig;

    private final ResultUtil resultUtil;

    public UserLoginSuccessHandler(JWTTokenUtil jwtTokenUtil, JWTConfig jwtConfig, ResultUtil resultUtil) {
        this.jwtTokenUtil = jwtTokenUtil;
        this.jwtConfig = jwtConfig;
        this.resultUtil = resultUtil;
    }

    /**
     * 登录成功返回结果
     *
     * @author uaniheng
     * @since 2019/10/3 9:27
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        List<String> authorities = authentication.getAuthorities().stream()
                .map(GrantedAuthority::getAuthority).collect(Collectors.toList());
        // 组装JWT
        Map<String, Object> claims = new HashMap<>();
        claims.put("authorities", authorities);
        String token = jwtTokenUtil.createAccessToken(UUID.randomUUID().toString(), authentication.getName(), claims);
        token = jwtConfig.getTokenPrefix() + token;
        // 封装返回参数
        Map<String, Object> resultData = new HashMap<>();
        resultData.put("code", "200");
        resultData.put("msg", "登录成功");
        resultData.put("token", token);
        resultUtil.responseJson(response, resultData);
    }
}